library('foreign')

###################################################
########### build peer risk, ch, factors, risk levels
###################################################

ones=rep(1,length(Peerz$numzz))

# if risk score is missing, replace overlap with zero in peermatrix
peermatrixsh=peermatrix
peermatrixsh[,is.na(Peerz$rskscr)]=0
totdaysh=peermatrixsh%*%ones

# replace missing values with zeros
Peerz$chscr[is.na(Peerz$chscr)]=0
Peerz$rskscr[is.na(Peerz$rskscr)]=0

# make the data frame
peermeasures=data.frame(numzz=Peerz$numzz)

#Create CH and Risk peer measures
peermeasures$peerch=as.matrix(peermatrixsh %*% Peerz$chscr / totdaysh)
peermeasures$peerrsk=as.matrix(peermatrixsh %*% Peerz$rskscr / totdaysh)
peermeasures$ph_gangz=as.matrix(peermatrixsh %*% Peerz$gangz / totdaysh)

# Create peer risk level variables
x=as.matrix(peermatrixsh %*% Peerz$chlev1 / totdaysh)
peermeasures$pchlev1=x
x=as.matrix(peermatrixsh %*% Peerz$chlev2 / totdaysh)
peermeasures$pchlev2=x
x=as.matrix(peermatrixsh %*% Peerz$chlev3 / totdaysh)
peermeasures$pchlev3=x
x=as.matrix(peermatrixsh %*% Peerz$chlev4 / totdaysh)
peermeasures$pchlev4=x
x=as.matrix(peermatrixsh %*% Peerz$chlev5 / totdaysh)
peermeasures$pchlev5=x
x=as.matrix(peermatrixsh %*% Peerz$chlev6 / totdaysh)
peermeasures$pchlev6=x
x=as.matrix(peermatrixsh %*% Peerz$chlev7 / totdaysh)
peermeasures$pchlev7=x
x=as.matrix(peermatrixsh %*% Peerz$chlev8 / totdaysh)
peermeasures$pchlev8=x
x=as.matrix(peermatrixsh %*% Peerz$chlev9 / totdaysh)
peermeasures$pchlev9=x


write.dta(peermeasures, file="PeerDay_ReSTAT.dta")
